package com.vincce.sport.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.SysResource;
import com.vincce.sport.entity.SysRole;
import com.vincce.sport.entity.SysUser;
import com.vincce.sport.mapper.SysResourceMapper;
import com.vincce.sport.mapper.SysRoleMapper;
import com.vincce.sport.mapper.SysUserMapper;



/**
 * Created with IntelliJ IDEA.
 * Date: 3/10/14
 * Time: 5:33 PM
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class BaseController {
	
	public static Logger LOG = Logger.getLogger(BaseController.class);
	
	@Resource
	private SysResourceMapper sysResourceMapper;
	
	@Resource
	private SysRoleMapper sysRoleMapper;
	
	@Resource
	private SysUserMapper sysUserMapper;
    /**
     * 获取当前登录用户
     * @return
     */
    public SysUser getCurrentUser () {
        return (SysUser)SecurityUtils.getSubject().getPrincipal();
    }
    
    public void sessionPutResource(HttpServletRequest request) throws IOException{
        List<SysRole> roleList = sysRoleMapper.findRoleByUserId(getCurrentUser().getId());
        
        List<SysResource> resourceAllList = sysResourceMapper.findAllSysResource();
        request.getSession().setAttribute("resourceAllList", resourceAllList);
        
        String roleIds = "";
		for(int i = 0; i < roleList.size(); i++){
			if(i == roleList.size() - 1){
				roleIds += roleList.get(i).getId();
			}else{
				roleIds += roleList.get(i).getId()+",";
			}
		}
        List<SysResource> resourceList = sysResourceMapper.findResourceByRoleId(roleIds);
        request.getSession().setAttribute("resourceRoleList", resourceList);
    }

    /**
     * 更新侧边条session
     * @param request
     */
    public void sessionPutNodeResource(HttpServletRequest request) throws IOException {
        SysUser user = getCurrentUser();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userId", user.getId());
        map.put("parentId",0);
    	List<SysResource> resourceList = sysResourceMapper.findResourceByAdminId(map);
    	if(!CheckUtil.isEmpty(resourceList)) {
            for(SysResource resource : resourceList) {
                map.put("parentId", resource.getId());
                List<SysResource> childList = sysResourceMapper.findResourceByAdminId(map);
                resource.setChildList(childList);
            }
        }
        request.getSession().setAttribute("NodeResources",resourceList);
    }
    
    /**
     * 富文本编辑器图片上传
     * @param model
     * @param request
     * @return
     * @throws IOException
     */
    /*@RequestMapping("/upload/image")
    public String upload(Model model, HttpServletRequest request) throws IOException{
        String msg="";
        Map<String, Object> result = new HashMap<String, Object>();

        // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
        MultipartFile file = multipartRequest.getFile("imgFile");
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        if (file != null && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
                msg="{\n" +
                        "        \"error\" : 1,\n" +
                        "        \"message\" : \"格式不正确,只支持后缀名为.jpg或者.png的图片上传。\"\n" +
                        "}";

            }else{
                obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);

                if (obj.statusCode == 200) {
                    String path=String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+obj.info.replaceAll("\\\\", "/"), "ori");
                    msg="{\n" +
                            "        \"error\" : 0,\n" +
                            "        \"url\" : \""+path+"\"\n" +
                            "}";
                    System.out.print("[--------------------------------------------------------------------------------"+path);
                }
            }
        }else{
            msg="{\n" +
                    "        \"error\" : 1,\n" +
                    "        \"message\" : \"请选择文件!\"\n" +
                    "}";

        }
       return msg;
    }*/
    
    /**
     * ip过滤，true通过，false不通过
     * @param request
     * @return
     */
    public boolean checkIp(HttpServletRequest request){
		boolean flag = false;
		String remoteAddr = request.getRemoteAddr();
		LOG.debug("********************  ip : " + remoteAddr);
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ip.properties");
		Properties p = new Properties();
		try {
			p.load(inputStream);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String ipList = p.getProperty("ip");
		String[] ips = ipList.split(",");
		for(String ip : ips){
			if(ip.equals(remoteAddr)){
				flag = true;
				break;
			}
		}
		return flag;
	}

}
